#!/usr/bin/env python
import os
import cgi
import logging
import wsgiref.handlers

from google.appengine.ext.webapp import template
from google.appengine.api import users
from google.appengine.ext import webapp

from django.utils import simplejson as json

from feeds_model import FeedCache
from searches_model import SavedSearch

class MainHandler(webapp.RequestHandler):
  
  def get(self):
    user = users.get_current_user()
    t_values = {}
    
    if user:
      t_values['logout_url'] = users.create_logout_url(self.request.uri)
      t_values['user'] = user
      t_values['active_tabs'] = ['welcome','settings']
      if users.is_current_user_admin():
          t_values['active_tabs'].append('admin')
      
      path = os.path.join(os.path.dirname(__file__), 'views/index.html')
      self.response.out.write(template.render(path, t_values))
    
    else:
      t_values['active_tabs'] = ['welcome',]
      t_values['login_url'] = users.create_login_url("/")
      
      path = os.path.join(os.path.dirname(__file__), 'views/index.html')
      self.response.out.write(template.render(path, t_values))


class TabsHandler(webapp.RequestHandler):
  """"""
  def get(self,tab_name):
    t_values = {}
    
    user = users.get_current_user()
    
    # logged in user
    if user:
      t_values['user'] = user
      
      if tab_name.lower() == "settings":
        q = SavedSearch.all()
        q.filter("user =", user)
        q.filter("name = ", "default")
        t_values["default_search"] = q.fetch(1)[0]
      
    else:
      t_values['login_url'] = users.create_login_url("/")
    
    path = os.path.join(os.path.dirname(__file__), 'views/tabs/' + tab_name + '.html')
    self.response.out.write(template.render(path,t_values))

class SavedSearchHandler(webapp.RequestHandler):
  """
  """
  def get(self, search_name, action, object_type, object_key):
    user = users.get_current_user()
    
    if user:
      # Lookup SavedSearch
      query = SavedSearch.all()
      query.filter("user =", user)
      query.filter("name =", search_name)
      saved_search = query.fetch(1)[0]
      
      if saved_search:
        if action.lower() == "delete":
          if object_type == "term":
            saved_search.delete_search_term(object_key)
            self.redirect("/")
        
        if action.lower() == "add":
          pass


class FeedUpdateHandler(webapp.RequestHandler):
  """
  Update one or more feed caches
  """
  def get(self):
    update_results = {}
    self.response.headers["Content-Type"] = "text/plain"
    
    # Single Feed Update
    feed_url = cgi.escape(self.request.get('feed'))
    if feed_url:
      feed = FeedCache.get_by_key_name(feed_url)
      if feed:
        update_results[feed.name] = FeedCache.get_by_key_name(feed_url).update_cache()
    
    # Update All Feeds
    else:
      for feed in FeedCache.all():
        update_results[feed.name] = feed.update_cache()
    
    # JSON output of update results
    self.response.out.write( json.JSONEncoder().encode(update_results) )
      
      

def main():
  application = webapp.WSGIApplication([
                                        ('/', MainHandler),
                                        (r'/tabs/(.*)', TabsHandler),
                                        (r'/saved_search/(.+)/(.+)/(.+)/(.+)', SavedSearchHandler),
                                        ('/feed/update', FeedUpdateHandler),
                                       ],
                                       debug=True)
  
  wsgiref.handlers.CGIHandler().run(application)


if __name__ == '__main__':
  main()
